//
//  LLToModelExtension.swift
//  LLProgramFrameworkSwift
//
//  Created by 奥卡姆 on 2017/9/7.
//  Copyright © 2017年 aokamu. All rights reserved.
//

import Foundation

import RxSwift
import Moya

extension Observable{

    //
    func mapObject<T:Decodable>(type: T.Type) -> Observable<T> {
        return self.map { response in
            guard let dict = response as? [String : Any] else{
                throw RxSwiftMoyaError.ParseJSONError
            }
            do {
                let data = try JSONSerialization.data(withJSONObject: dict, options: [])
                let model = try JSONDecoder().decode(T.self, from: data)
                return model
            } catch {
                // 异常处理
                throw RxSwiftMoyaError.ParseJSONError
            }
        }
    }
        
    func mapArray<T: Decodable>(type: T.Type) -> Observable<[T]> {
        return self.map { response in
            //if response is an array of dictionaries, then use ObjectMapper to map the dictionary
            //if not, throw an error
            guard let array = response as? [Any] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            
            guard let dicts = array as? [[String: Any]] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            do {
                let data = try JSONSerialization.data(withJSONObject: dicts, options: [])
                let model = try JSONDecoder().decode([T].self, from: data)
                return model
            } catch {
                // 异常处理
                throw RxSwiftMoyaError.ParseJSONError
            }
        }
    }

    
    
    
}

enum RxSwiftMoyaError: String {
    case ParseJSONError
    case OtherError
}

extension RxSwiftMoyaError: Swift.Error { }



